import 'dart:convert';
import 'dart:io';

import 'package:banner_view/banner_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/brands/brands_details_page.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/open_page_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/share_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/goods/goods_list_item_widget.dart';
import 'package:gzmall_app/goods/goods_list_widget.dart';
import 'package:gzmall_app/goods/home_goods_list_page.dart';
import 'package:gzmall_app/mine/order_details.dart';
import 'package:gzmall_app/mine/order_page.dart';
import 'package:gzmall_app/mine/select_regions.dart';
import 'package:gzmall_app/model/avatar.dart';
import 'package:gzmall_app/model/brand.dart';
import 'package:gzmall_app/model/hot_tag.dart';
import 'package:gzmall_app/model/location.dart';
import 'package:gzmall_app/model/product.dart';
import 'package:gzmall_app/model/regions.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:gzmall_app/topup/topup_page.dart';
import "package:pull_to_refresh/pull_to_refresh.dart";
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:async';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/model/advertisement.dart';
import 'package:gzmall_app/model/channel.dart';
import 'package:gzmall_app/model/seckills.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:amap_location/amap_location.dart';
import 'package:gzmall_app/store/near_store_list_page.dart';
import 'package:dio/dio.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'package:gzmall_app/model/head_line.dart';
import 'package:gzmall_app/home/clearance_list_page.dart';
import 'package:gzmall_app/home/actives_page.dart';
import 'package:gzmall_app/home/brand_list_page.dart';
import 'package:gzmall_app/shoppping_cart/buy_success.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:gzmall_app/model/notices.dart';
import 'package:gzmall_app/model/setting.dart';
// import 'package:simple_permissions/simple_permissions.dart';
import 'package:permission_handler/permission_handler.dart';

class HomeWidget extends StatefulWidget {
  Function onSelectTab;

  HomeWidget({this.onSelectTab});
  @override
  HomeWidgetState createState() {
    return new HomeWidgetState(onSelectTab: this.onSelectTab);
  }
}

class HomeWidgetState extends State<HomeWidget> {
  Function onSelectTab;

  User _user = User.empty();

  double _topPadding;
  double _bottomPadding;

  var _funTitles;
  var _funImages;

  List<Advertisement> _advertisementImages = [];
  List<Product> _recommendProduct = [];
  List<Brand> _brands = [];
  List<Channel> _channels = [];
  List<Seckills> _seckills = [];
  List<Advertisement> _homeAdvertisements = [];
  List<HeadLine> _headLines = [];
  List<Notices> _notices = [];
  List<HotTag> _hotTags = [];
  List<Setting> _settings = [];

  String _location = "未定位", _latitude = "", _longitude = "", _adcode = "";
  int _regionLevel = 3;

  double _itemWidth;

  RefreshListView _refreshListView;

  HomeWidgetState({this.onSelectTab});

  @override
  void initState() {
    super.initState();
    if (SettingUtil.cityOrDistrict != null &&
        SettingUtil.cityOrDistrict.isNotEmpty) {
      if (SettingUtil.cityOrDistrict == "city") {
        setState(() {
          _regionLevel = 2;
        });
      } else if (SettingUtil.cityOrDistrict == "district") {
        setState(() {
          _regionLevel = 3;
        });
      }
    }
    _checkPersmission();
  }

  @override
  void dispose() {
    //注意这里关闭
    AMapLocationClient.stopLocation();
    AMapLocationClient.shutdown();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    init();
    return Container(
      decoration: new BoxDecoration(color: ColorCommon.grey2),
      child: new Column(
        children: <Widget>[
          _createTitleBar(),
          new Expanded(
            child: _createRefresh(context),
          ),
        ],
      ),
    );
  }

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
    _bottomPadding = MediaQuery.of(context).padding.bottom;

    var size = MediaQuery.of(context).size;
    _itemWidth = (size.width - 12) / 2;

    _funTitles = [
      "彩妆",
      "鞋包",
      "手机",
      "电器",
      "食品",
      "百货",
      "服饰",
      "家装",
      "分享好友",
      "领券中心",
    ];
    _funImages = [
      "images/fun_1.png",
      "images/fun_2.png",
      "images/fun_3.png",
      "images/fun_4.png",
      "images/fun_5.png",
      "images/fun_6.png",
      "images/fun_7.png",
      "images/fun_8.png",
      "images/fun_9.png",
      "images/fun_10.png",
    ];
  }

  Widget _createTitleBar() {
    List<Widget> _hotTagWidgets = [];
    if (_hotTags != null && _hotTags.length > 0) {
      _hotTagWidgets = _hotTags.map((t) {
        return _getRecommendBtn(t?.name ?? "", () {
          OpenPageUtil.openPage(context, t?.pageType, t?.pageUrl, t?.params,
              name: t?.name,
              latitude: _latitude,
              longitude: _longitude,
              adcode: _adcode,
              uid: _user?.id?.toString());
        });
      }).toList();
    }
    return new Container(
      padding: EdgeInsets.fromLTRB(10.0, _topPadding + 10.0, 10.0, 10.0),
      color: ColorCommon.primaryColor,
      child: new Column(
        children: <Widget>[
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Expanded(
                child: InkWell(
                  onTap: () {
                    // _checkPersmission();
                    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                      return SelectRegionsPage(
                        level: _regionLevel,
                      );
                    })).then((value) {
                      if (value != null) {
                        Regions r1, r2, r3;
                        switch (_regionLevel) {
                          case 1:
                            r1 = Regions.fromJson(value["1"]);
                            Location.saveLocationInfo(
                                r1.latitude, r1.longitude, r1.value, r1.adcode);
                            _location = r1?.value ?? "";
                            _latitude = r1.latitude;
                            _longitude = r1.longitude;
                            _adcode = r1.adcode;
                            break;
                          case 2:
                            r2 = Regions.fromJson(value["2"]);
                            Location.saveLocationInfo(
                                r2.latitude, r2.longitude, r2.value, r2.adcode);
                            _location = r2?.value ?? "";
                            _latitude = r2.latitude;
                            _longitude = r2.longitude;
                            _adcode = r2.adcode;
                            break;
                          case 3:
                            r3 = Regions.fromJson(value["3"]);
                            Location.saveLocationInfo(
                                r3.latitude, r3.longitude, r3.value, r3.adcode);
                            _location = r3?.value ?? "";
                            _latitude = r3.latitude;
                            _longitude = r3.longitude;
                            _adcode = r3.adcode;
                            break;
                          default:
                            r3 = Regions.fromJson(value["3"]);
                            Location.saveLocationInfo(
                                r3.latitude, r3.longitude, r3.value, r3.adcode);
                            _location = r3?.value ?? "";
                            _latitude = r3.latitude;
                            _longitude = r3.longitude;
                            _adcode = r3.adcode;
                        }

                        setState(() {
                          _location = _location != null && _location.isNotEmpty
                              ? _location
                              : "未获取定位信息";
                        });
                        _getData();
                      }
                    });
                  },
                  child: Row(
                    children: <Widget>[
                      new Image.asset(
                        "images/location.png",
                        width: 16.0,
                        height: 16.0,
                      ),
                      new Container(
                        padding: const EdgeInsets.only(left: 5.0),
                        child: new Text(
                          _location ?? "未定位",
                          style: new TextStyle(
                              color: Colors.white, fontSize: 15.0),
                        ),
                      ),
                      new Container(
                        padding: const EdgeInsets.only(left: 2.0, right: 5.0),
                        child: new Text(
                          "",
                          style: new TextStyle(
                              color: Colors.white, fontSize: 10.0),
                        ),
                      ),
                      new Image.asset(
                        "images/arrow-down.png",
                        width: 10.0,
                        height: 10.0,
                        alignment: Alignment.centerRight,
                      ),
                    ],
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  _scan();
                },
                child: new Container(
                  padding: const EdgeInsets.only(right: 10.0),
                  child: new Image.asset(
                    "images/scan.png",
                    width: 16.0,
                    height: 16.0,
                    alignment: Alignment.centerRight,
                  ),
                ),
              ),
              new InkWell(
                onTap: () {
                  Navigator.of(context).pushNamed('/message_center_page');
                },
                child: Image.asset(
                  "images/message.png",
                  width: 16.0,
                  height: 16.0,
                  alignment: Alignment.centerRight,
                ),
              ),
            ],
          ),
          new GestureDetector(
            child: new Container(
              height: 27.0,
              margin: const EdgeInsets.only(top: 12.0),
              padding: const EdgeInsets.only(left: 8.0, right: 8.0),
              decoration: new BoxDecoration(
                  color: ColorCommon.translucent1,
                  borderRadius: new BorderRadius.circular(100.0)),
              child: new Row(
                children: <Widget>[
                  new Padding(
                    padding: const EdgeInsets.only(right: 8.0),
                    child: new Image.asset(
                      'images/search.png',
                      width: 16.0,
                      height: 16.0,
                    ),
                  ),
                  new Text(
                    "搜索",
                    style: new TextStyle(color: Colors.white),
                  ),
                ],
              ),
            ),
            onTap: () {
              Navigator.of(context).pushNamed('/search_goods_page');
            },
          ),
          Padding(
              padding: const EdgeInsets.only(top: 10.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.0),
                    child: Text(
                      "推荐",
                      style: TextStyle(color: Colors.white, fontSize: 13.0),
                    ),
                  ),
                  Expanded(
                    child: Row(
                      children: _hotTagWidgets,
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  Widget _getRecommendBtn(String text, Function onTap) {
    Color _bgColor = ColorCommon.translucent1,
        _borderColor = Colors.transparent,
        _fontColor = Colors.white;
    double width = (MediaQuery.of(context).size.width - 20.0 - 20.0 - 40.0) / 4;
    return Expanded(
        child: InkWell(
            onTap: onTap,
            child: Container(
                height: 22.0,
                width: width,
                alignment: Alignment.center,
                margin: const EdgeInsets.only(right: 10.0),
                padding: const EdgeInsets.symmetric(horizontal: 5.0),
                decoration: BoxDecoration(
                    color: _bgColor,
                    border: Border.all(color: _borderColor),
                    borderRadius: BorderRadius.all(Radius.circular(5.0))),
                child: Text(
                  text,
                  style: TextStyle(fontSize: 13.0, color: _fontColor),
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ))));
  }

  Widget _createRefresh(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: ListView(
        padding: EdgeInsets.only(top: 0.0),
        children: <Widget>[
          _createFunView(),
          // _createActivityView(),
          _createMarqueeWidget(),
          _createHeadLineView(),
          // _createOtherEntranceView(),
          _getTipsTitle("热销品牌"),
          _createChoseView(),
          _getTipsTitle("为你推荐"),
          // _createRecommendView(),
          _buildRecommendGirdList(),
        ],
      ),
    );
    return _refreshListView;
  }

  Widget _getTipsTitle(String title) {
    return new Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.only(top: 22.0, bottom: 16.0),
      child: new Text(
        title,
        style: new TextStyle(fontSize: 19.0, color: ColorCommon.black2),
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getData();
      new Future.delayed(const Duration(milliseconds: 2000)).then((val) {
        if (_refreshListView != null) {
          _refreshListView.refreshCompleted(up);
        }
      });
    } else {
      _getRecommend(false);
    }
  }

  void _onOffsetChange(bool up, double offset) {}

  Widget _createFunView() {
    List<Channel> c1 = [];
    List<Channel> c2 = [];
    if (_channels != null && _channels.length > 0) {
      for (var i = 0; i < _channels.length; i++) {
        if (i < 5) {
          c1.add(_channels[i]);
        } else if (i >= 5 && i < 10) {
          c2.add(_channels[i]);
        }
      }
    }
    int _c1Index = 0, _c2Index = 0;
    return new Stack(
      children: <Widget>[
        new Container(
          alignment: Alignment.topCenter,
          height: 280.0,
          child: _advertisementImages != null && _advertisementImages.length > 0
              ? _createBannerView(_advertisementImages)
              : Container(height: 175.0),
        ),
        new Positioned(
          bottom: 0.0,
          left: 0.0,
          right: 0.0,
          child: new Card(
            elevation: 0.0,
            margin: const EdgeInsets.only(left: 10.0, right: 10.0),
            child: new Column(
              children: <Widget>[
                new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: c1 != null && c1.length > 0
                      ? c1.map((i) {
                          return _getFunView(_c1Index++, c1.length, i);
                        }).toList()
                      : <Widget>[Container()],
                ),
                new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: c2 != null && c2.length > 0
                      ? c2.map((i) {
                          return _getFunView(_c2Index++, c2.length, i);
                        }).toList()
                      : <Widget>[Container()],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _getFunView(int index, int total, Channel channel) {
    BorderSide _side = new BorderSide(color: ColorCommon.grey2, width: 1.0);
    BorderSide _sideNull =
        new BorderSide(color: Colors.transparent, width: 1.0);
    BorderSide _bottom, _left, _right;
    if (index < total) {
      _bottom = _side;
    } else {
      _bottom = _sideNull;
    }
    if ((index + 1) % total > 0) {
      _right = _side;
      _left = _sideNull;
    } else {
      _right = _sideNull;
      _left = _sideNull;
    }
    return channel.pageType == "Share" &&
            (!LaunchUtil.isInstallWeixin || SettingUtil.isAppStoreAudit())
        ? Container()
        : new Expanded(
            child: new GestureDetector(
              onTap: () {
                if (channel?.pageType == 'Native' &&
                    channel?.pageUrl == 'category_widget' &&
                    this.onSelectTab != null) {
                  this.onSelectTab(1, channel?.params);
                  return;
                }
                OpenPageUtil.openPage(context, channel?.pageType,
                    channel?.pageUrl, channel?.params,
                    name: channel?.name,
                    latitude: _latitude,
                    longitude: _longitude,
                    adcode: _adcode,
                    uid: _user?.id?.toString(),
                    shareTitle: channel?.shareTitle,
                    shareAvatar: channel?.shareAvatar,
                    shareContent: channel?.shareContent,
                    showTips: '该频道暂未开放');
              },
              child: new Container(
                height: 70.0,
                alignment: Alignment.center,
                // 去掉分割线
                // decoration: new BoxDecoration(
                //   border: new Border(
                //     bottom: _bottom,
                //     left: _left,
                //     right: _right,
                //   ),
                // ),
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    CachedNetworkImage(
                      imageUrl: channel.avatar,
                      width: 35.0,
                      height: 35.0,
                      fit: BoxFit.fill,
                    ),
                    new Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: new Text(
                        channel.name,
                        style: new TextStyle(fontSize: 10.0),
                        maxLines: 1,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
  }

  Widget _createMarqueeWidget() {
    return _notices != null && _notices.length > 0
        ? Container(
            color: Colors.white,
            width: double.infinity,
            alignment: Alignment.centerLeft,
            margin:
                const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0),
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Row(
              children: <Widget>[
                Image.asset("images/ic_announcement.jpeg",
                    width: 15.0, height: 15.0),
                Expanded(
                  child: Container(
                    height: 30.0,
                    margin: const EdgeInsets.only(left: 10.0),
                    child: Swiper(
                      itemBuilder: (BuildContext context, int index) {
                        return Align(
                          alignment: Alignment.centerLeft,
                          child: Text(_notices[index].name,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: 12.0,
                                  color: ColorCommon.primaryColor)),
                        );
                      },
                      itemCount: _notices.length,
                      scrollDirection: Axis.vertical,
                      autoplay: true,
                      loop: true,
                    ),
                  ),
                ),
              ],
            ),
          )
        : Container();
  }

  Widget _createHeadLineView() {
    List<Widget> _headLinesView = [];
    if (_headLines != null && _headLines.length > 0) {
      for (var i in _headLines) {
        _headLinesView.add(_getHeadLineItemView(i));
      }
    }
    return new Card(
      elevation: 0.0,
      margin: const EdgeInsets.only(left: 10.0, right: 10.0),
      child: new Wrap(
        children: _headLinesView,
      ),
    );
  }

  Widget _getHeadLineItemView(HeadLine headLine) {
    var _itemWidth = (MediaQuery.of(context).size.width - 10 - 10 - 2) / 2;
    List<Widget> _imageWidget = [];
    if (headLine.items != null && headLine.items.length > 0) {
      for (var i = 0; i < headLine.items.length; i++) {
        if (i < 2) {
          _imageWidget.add(Padding(
            padding: const EdgeInsets.only(bottom: 5.0, top: 10.0),
            child: CachedNetworkImage(
              imageUrl: headLine.items[i].avatar,
              width: (_itemWidth - 8 - 8 - 8) / 2,
              height: 50.0,
              fit: BoxFit.fill,
            ),
          ));
        }
      }
    }
    return InkWell(
        onTap: () {
          OpenPageUtil.openPage(
              context, headLine?.type, headLine?.page, headLine?.params,
              name: headLine?.name,
              latitude: _latitude,
              longitude: _longitude,
              adcode: _adcode,
              uid: _user?.id?.toString());
        },
        child: Container(
          width: _itemWidth,
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          decoration: new BoxDecoration(
              border: Border(
            right: new BorderSide(color: ColorCommon.grey2, width: 1.0),
            bottom: new BorderSide(color: ColorCommon.grey2, width: 1.0),
          )),
          child: new Column(children: <Widget>[
            new Row(
              children: <Widget>[
                new Expanded(
                  child: new Container(
                    height: 18.0,
                    alignment: Alignment.centerLeft,
                    padding: const EdgeInsets.only(left: 8.0),
                    child: new Text(
                      headLine.name,
                      textAlign: TextAlign.left,
                      style: new TextStyle(
                          fontSize: 16.0,
                          color: ColorCommon.black2,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
              ],
            ),
            new Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: _imageWidget,
            ),
          ]),
        ));
  }

  Widget _createActivityView() {
    List<Widget> _activityView = [];
    if (_seckills != null && _seckills.length > 0) {
      for (var i = 0; i < _seckills.length; i++) {
        if (i < 2) {
          _activityView
              .add(new Expanded(child: _getActivityView(i == 0, _seckills[i])));
        } else {
          break;
        }
      }
    }
    return new Card(
      elevation: 0.0,
      margin: const EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
      child: new Row(
        children: _activityView,
      ),
    );
  }

  Widget _getActivityView(bool isProceeding, Seckills seckills) {
    return new Container(
      padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
      decoration: new BoxDecoration(
          border: Border(
              right: new BorderSide(color: ColorCommon.grey2, width: 1.0))),
      child: new Column(children: <Widget>[
        new Row(
          children: <Widget>[
            new Expanded(
              child: new Container(
                padding: const EdgeInsets.only(left: 8.0),
                child: new Text(
                  isProceeding ? "限时购" : "每日更新",
                  textAlign: TextAlign.left,
                  style: new TextStyle(
                      fontSize: 16.0,
                      color: ColorCommon.black2,
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
            _getActivityInfoView(
                isProceeding, seckills.startTimeAt, seckills.endTimeAt),
          ],
        ),
        new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            _getActivityProductView(seckills.spu),
            _getActivityProductView(seckills.spu),
          ],
        ),
      ]),
    );
  }

  Widget _getActivityProductView(Product product) {
    return InkWell(
        onTap: () {
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new GoodsDetailsPage(productId: product.id);
          }));
        },
        child: new Column(
          children: <Widget>[
            new Padding(
              padding: const EdgeInsets.only(bottom: 5.0, top: 15.0),
              child: CachedNetworkImage(
                imageUrl: product.avatar,
                width: 40.0,
                height: 40.0,
              ),
            ),
            new Row(
              children: <Widget>[
                new Text(
                  "¥" + product.lowSalePrice,
                  style: new TextStyle(fontSize: 16.0, color: ColorCommon.red2),
                ),
                new Text(
                  "¥" + product.lowSalePrice,
                  style: new TextStyle(fontSize: 8.0, color: ColorCommon.grey3),
                )
              ],
            ),
          ],
        ));
  }

  Widget _getActivityInfoView(
      bool isProceeding, String startTime, String endTime) {
    // TextStyle _timeStyle =
    //     new TextStyle(fontSize: 10.0, color: ColorCommon.grey3);
    // BoxDecoration _timeDecoration = new BoxDecoration(
    //     color: ColorCommon.black2,
    //     borderRadius: BorderRadius.all(const Radius.circular(2.0)));
    if (isProceeding) {
      // return new Container(
      //   padding: const EdgeInsets.only(right: 8.0),
      //   alignment: Alignment.centerRight,
      //   child: new Row(
      //     children: <Widget>[
      //       new Container(
      //         decoration: _timeDecoration,
      //         child: new Text(
      //           "09",
      //           style: _timeStyle.copyWith(color: Colors.white),
      //         ),
      //       ),
      //       new Text(
      //         ":",
      //         style: _timeStyle,
      //       ),
      //       new Container(
      //         decoration: _timeDecoration,
      //         child: new Text(
      //           "09",
      //           style: _timeStyle.copyWith(color: Colors.white),
      //         ),
      //       ),
      //       new Text(
      //         ":",
      //         style: _timeStyle,
      //       ),
      //       new Container(
      //         margin: const EdgeInsets.only(right: 4.0),
      //         decoration: _timeDecoration,
      //         child: new Text(
      //           "09",
      //           style: _timeStyle.copyWith(color: Colors.white),
      //         ),
      //       ),
      //       new Text(
      //         "9点场",
      //         style: _timeStyle,
      //       ),
      //     ],
      //   ),
      // );
      return Container();
    } else {
      return new Container(
        padding: const EdgeInsets.only(right: 8.0),
        alignment: Alignment.centerRight,
        child: new Text(
          startTime + " 折扣超前",
          textAlign: TextAlign.right,
          style: new TextStyle(fontSize: 8.0, color: ColorCommon.grey3),
        ),
      );
    }
  }

  Widget _createOtherEntranceView() {
    return new Card(
      elevation: 0.0,
      margin: const EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
      child: new Row(
        children: <Widget>[
          new Expanded(
            child: _getOtherEntranceView(
                "附近的门店", "逛遍全球", "images/fun_1.png", false, () {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return NearStoreListPage(
                  latitude: _latitude,
                  longitude: _longitude,
                  adcode: _adcode,
                );
              }));
            }),
          ),
          new Expanded(
            child: _getOtherEntranceView(
                "家居生活", "居住指南", "images/fun_1.png", true, () {}),
          ),
          new Expanded(
            child: _getOtherEntranceView(
                "产品严选", "甄选只为你", "images/fun_1.png", false, () {}),
          ),
        ],
      ),
    );
  }

  Widget _getOtherEntranceView(String title, String subContent, String iconPath,
      bool isBorder, Function onTap) {
    BorderSide _side = new BorderSide(color: ColorCommon.grey2, width: 1.0);
    BorderSide _sideNull =
        new BorderSide(color: Colors.transparent, width: 0.0);
    BoxDecoration _boxDecoration = new BoxDecoration(
      border: new Border(
          left: isBorder ? _side : _sideNull,
          right: isBorder ? _side : _sideNull),
    );
    return InkWell(
      onTap: onTap,
      child: new Container(
        padding: const EdgeInsets.only(top: 15.0, bottom: 15.0),
        decoration: _boxDecoration,
        child: new Column(
          children: <Widget>[
            new Text(
              title,
              style: new TextStyle(
                  fontSize: 16.0,
                  color: ColorCommon.black2,
                  fontWeight: FontWeight.bold),
            ),
            new Container(
              padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
              child: new Text(
                subContent,
                style: new TextStyle(fontSize: 10.0, color: ColorCommon.grey3),
              ),
            ),
            new Image.asset(
              iconPath,
              width: 60.0,
              height: 60.0,
            ),
          ],
        ),
      ),
    );
  }

  Widget _createChoseView() {
    Advertisement _adv;
    if (_homeAdvertisements != null && _homeAdvertisements.length > 0) {
      _adv = _homeAdvertisements[0];
    }
    return _brands != null && _brands.length > 0
        ? new Column(
            children: <Widget>[
              _getChoseView(1, _brands, _adv),
            ],
          )
        : Container();
  }

  Widget _getChoseView(int type, List<Brand> brands, Advertisement adv) {
    List<Widget> _subBrandWidget = [];
    if (brands.length > 0) {
      _subBrandWidget = brands
          .map((i) => InkWell(
                child: _getSubChoseView(type, i),
                onTap: () {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandsDetailsPage(id: i.id);
                  }));
                },
              ))
          .toList();
    }
    return new Column(
      children: <Widget>[
        adv != null && adv.image != null
            ? InkWell(
                onTap: () {
                  OpenPageUtil.openPage(
                      context, adv?.pageType, adv?.pageUrl, adv?.params,
                      name: adv?.name, uid: _user?.id?.toString());
                },
                child: Container(
                  height: 150.0,
                  width: MediaQuery.of(context).size.width,
                  margin: const EdgeInsets.only(
                      left: 10.0, right: 10.0, bottom: 10.0),
                  padding: const EdgeInsets.only(left: 30.0),
                  alignment: Alignment.centerLeft,
                  decoration: new BoxDecoration(
                    borderRadius: BorderRadius.all(const Radius.circular(5.0)),
                    image: new DecorationImage(
                        image: new CachedNetworkImageProvider(adv.image),
                        fit: BoxFit.fill),
                  ),
                  // child: new Column(
                  //   mainAxisAlignment: MainAxisAlignment.center,
                  //   crossAxisAlignment: CrossAxisAlignment.start,
                  //   children: <Widget>[
                  //     new Text(
                  //       _fBrand.name,
                  //       style:
                  //           new TextStyle(fontSize: 19.0, color: ColorCommon.black2),
                  //     ),
                  //     // new Text(
                  //     //   "酒业精品/酒业良选",
                  //     //   style: new TextStyle(fontSize: 12.0, color: ColorCommon.black2),
                  //     // ),
                  //   ],
                  // ),
                ),
              )
            : Container(),
        new Container(
          height: type == 1 ? 135.0 : 95.0,
          margin: const EdgeInsets.only(left: 10.0, bottom: 10.0),
          child: new ListView(
            scrollDirection: Axis.horizontal,
            children: _subBrandWidget,
          ),
        ),
      ],
    );
  }

  Widget _getSubChoseView(int type, Brand brand) {
    switch (type) {
      case 1:
        return new Card(
          elevation: 0.0,
          margin: const EdgeInsets.only(right: 10.0),
          child: new Column(
            children: <Widget>[
              new Container(
                width: 95.0,
                height: 95.0,
                decoration: new BoxDecoration(
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(5.0),
                      topRight: Radius.circular(5.0)),
                  image: new DecorationImage(
                    image: new CachedNetworkImageProvider(brand.avatar),
                    fit: BoxFit.fill,
                  ),
                ),
              ),
              new Container(
                height: 40.0,
                alignment: Alignment.center,
                child: new Text(brand.name),
              ),
            ],
          ),
        );
      default:
        return new Container(
          width: 95.0,
          margin: const EdgeInsets.only(right: 10.0),
          decoration: new BoxDecoration(
            borderRadius: BorderRadius.all(const Radius.circular(5.0)),
            image: new DecorationImage(
                image: new CachedNetworkImageProvider(brand.avatar),
                fit: BoxFit.fill),
          ),
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text(brand.name),
              // new Text(
              //   "酒业精品/酒业良选",
              //   style: new TextStyle(fontSize: 8.0, color: ColorCommon.black2),
              // ),
            ],
          ),
        );
    }
  }

  Widget _createRecommendView() {
    List<Widget> _recommendProductWidget = [];
    if (_recommendProduct != null && _recommendProduct.length > 0) {
      _recommendProductWidget =
          _recommendProduct.map((i) => _getRecommendProductView(i)).toList();
    } else {
      _recommendProductWidget.add(Container());
    }
    return new Column(
      children: _recommendProductWidget,
    );
  }

  Widget _buildRecommendGirdList() {
    List<Widget> spuList = _recommendProduct
        .map((item) => new InkWell(
              child: new GoodsListItemWidget(item, _itemWidth),
              onTap: () {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new GoodsDetailsPage(productId: item.id);
                }));
              },
            ))
        .toList();
    return GridView.count(
      shrinkWrap: true,
      padding: const EdgeInsets.only(left: 4.0, right: 4.0, top: 4.0),
      crossAxisSpacing: 4.0,
      mainAxisSpacing: 4.0,
      controller: new ScrollController(keepScrollOffset: false),
      crossAxisCount: 2,
      childAspectRatio: 0.65,
      children: spuList,
    );
  }

  Widget _getRecommendProductView(Product product) {
    return InkWell(
      onTap: () {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new GoodsDetailsPage(productId: product.id);
        }));
      },
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.all(10.0),
        margin: const EdgeInsets.only(bottom: 10.0),
        child: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                new CachedNetworkImage(
                  width: 150.0,
                  height: 150.0,
                  imageUrl: product?.avatar,
                  fit: BoxFit.fill,
                ),
                new Expanded(
                  child: new Padding(
                    padding: const EdgeInsets.only(left: 10.0),
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        new Text(
                          product != null ? product.name : "",
                          style: new TextStyle(
                              fontSize: 19.0, color: ColorCommon.black2),
                        ),
                        new Padding(
                          padding: const EdgeInsets.only(top: 4.0, bottom: 8.0),
                          child: new Text(
                            product != null && product.shopCategory != null
                                ? product.shopCategory.name
                                : "",
                            style: new TextStyle(
                                fontSize: 10.0, color: ColorCommon.black2),
                          ),
                        ),
                        product != null && product.brand != null
                            ? new Container(
                                padding: const EdgeInsets.only(
                                    left: 15.0,
                                    right: 15.0,
                                    top: 5.0,
                                    bottom: 5.0),
                                color: Colors.blue[300],
                                child: new Text(
                                  product.brand.name,
                                  style: new TextStyle(
                                      fontSize: 10.0, color: Colors.white),
                                ),
                              )
                            : Container(),
                        new Padding(
                          padding: const EdgeInsets.only(top: 10.0),
                          child: new Text(
                            "¥ " + product?.lowSalePrice.toString(),
                            style: new TextStyle(
                                fontSize: 16.0, color: ColorCommon.red2),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            new Padding(
              padding: const EdgeInsets.only(top: 20.0),
              child: new Row(
                children: <Widget>[
                  new Expanded(
                    child: new Row(
                      children: <Widget>[
                        _getTagView(product?.shopCategory?.name),
                        product != null && product.brand != null
                            ? new Padding(
                                padding: const EdgeInsets.only(left: 10.0),
                                child: _getTagView(product.brand.name),
                              )
                            : Container(),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new GoodsListWidget(
                            categoryId: product.shopCategory.id,
                            categoryName: product.shopCategory.name);
                      }));
                    },
                    child: _getMinButtonView(
                        "找相似", Colors.transparent, Colors.red, Colors.red),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _getTagView(String tag) {
    return new Container(
      padding: const EdgeInsets.fromLTRB(10.0, 4.0, 10.0, 4.0),
      decoration: new BoxDecoration(
        color: ColorCommon.grey2,
      ),
      child: new Text(
        tag,
        style: new TextStyle(fontSize: 13.0),
      ),
    );
  }

  Widget _getMinButtonView(
      String content, Color bgColor, Color borderColor, Color textColor) {
    return new Container(
      padding: const EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
      decoration: new BoxDecoration(
        color: bgColor,
        border: Border.all(color: borderColor, width: 1.0),
        borderRadius: const BorderRadius.all(Radius.circular(100.0)),
      ),
      child: new Text(
        content,
        style: new TextStyle(fontSize: 13.0, color: textColor),
      ),
    );
  }

  Widget _getRecommendCategoryView() {
    return new Card(
      elevation: 0.0,
      margin: const EdgeInsets.all(10.0),
      child: new Padding(
        padding: const EdgeInsets.only(
            top: 15.0, bottom: 15.0, left: 10.0, right: 10.0),
        child: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                new Expanded(
                  child: new Row(
                    children: <Widget>[
                      new Container(
                        width: 38.0,
                        height: 38.0,
                        decoration: new BoxDecoration(
                          borderRadius:
                              const BorderRadius.all(Radius.circular(100.0)),
                          image: new DecorationImage(
                            image: new CachedNetworkImageProvider(
                                "http://via.placeholder.com/350x150"),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: const EdgeInsets.only(left: 15.0),
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Text(
                              "分类名称",
                              style: new TextStyle(
                                  fontSize: 14.0, color: ColorCommon.black2),
                            ),
                            new Text(
                              "分类描述内容",
                              style: new TextStyle(
                                  fontSize: 10.0, color: ColorCommon.grey3),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                _getMinButtonView("+关注", Colors.red, Colors.red, Colors.white),
              ],
            ),
            new Padding(
              padding: const EdgeInsets.only(top: 15.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _getRecommendCategoryProductView(),
                  _getRecommendCategoryProductView(),
                  _getRecommendCategoryProductView(),
                  _getRecommendCategoryProductView(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _getRecommendCategoryProductView() {
    return new Expanded(
      child: new Padding(
        padding: const EdgeInsets.only(left: 2.0, right: 2.0),
        child: new Column(
          children: <Widget>[
            new CachedNetworkImage(
              imageUrl: "http://via.placeholder.com/350x150",
              fit: BoxFit.fill,
            ),
            new Padding(
              padding: const EdgeInsets.only(top: 8.0, bottom: 10.0),
              child: new Text(
                "商品名称",
                style: new TextStyle(fontSize: 10.0),
              ),
            ),
            new Text(
              "¥ 120.0",
              style: new TextStyle(fontSize: 12.0, color: Colors.red),
            )
          ],
        ),
      ),
    );
  }

  _createBannerView(List<Advertisement> images) {
    return Container(
      alignment: Alignment.center,
      height: 175.0,
      child: BannerView(
        _getBannerImage(images),
        log: false,
        indicatorMargin: 10.0,
        indicatorNormal: _indicatorItem(ColorCommon.grey7),
        indicatorSelected:
            _indicatorItem(ColorCommon.primaryColor, selected: true),
        indicatorBuilder: (context, indicator) {
          return _indicatorContainer(indicator);
        },
        intervalDuration: Duration(seconds: 3),
        animationDuration: Duration(milliseconds: 500),
      ),
    );
  }

  List<Widget> _getBannerImage(List<Advertisement> images) {
    return images.map((e) {
      return GestureDetector(
        onTap: () {
          OpenPageUtil.openPage(context, e?.pageType, e?.pageUrl, e?.params,
              name: e?.name, uid: _user?.id?.toString());
        },
        child: CachedNetworkImage(
          imageUrl: e.image,
          fit: BoxFit.fill,
        ),
      );
    }).toList();
  }

  Widget _indicatorContainer(Widget indicator) {
    var container = Container(
      height: 30.0,
      margin: const EdgeInsets.only(bottom: 30.0),
      child: Stack(
        children: <Widget>[
          Container(
            color: Colors.transparent,
          ),
          Align(
            alignment: Alignment.center,
            child: indicator,
          ),
        ],
      ),
    );

    return Align(
      alignment: Alignment.bottomCenter,
      child: container,
    );
  }

  Widget _indicatorItem(Color color, {bool selected = false}) {
    double width = selected ? 18.0 : 6.0;
    return Container(
      width: width,
      height: 4.0,
      decoration: BoxDecoration(
        color: color,
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.all(
          Radius.circular(5.0),
        ),
      ),
    );
  }

  _startLocation() async {
    AMapLocation loc = await AMapLocationClient.getLocation(true);
    _handLocation(loc);

    // AMapLocationClient.onLocationUpate.listen((AMapLocation loc) {
    //   if (!mounted) return;
    //   if (loc != null) {
    //     _latitude = loc.latitude.toString();
    //     _longitude = loc.longitude.toString();
    //     _adcode = loc.adcode ?? "";

    //     switch (_regionLevel) {
    //       case 1:
    //         // 省级名称
    //         _location = loc?.province ?? "";
    //         break;
    //       case 2:
    //         // 市级名称
    //         _location = loc?.city ?? (loc?.province ?? "");
    //         break;
    //       case 3:
    //         // 县区级名称
    //         _location = loc?.district ?? (loc?.city ?? (loc?.province ?? ""));
    //         break;
    //       default:
    //         _location = loc?.district ?? (loc?.city ?? (loc?.province ?? ""));
    //     }
    //     if (_location != null && _location.isNotEmpty) {
    //       Location.saveLocationInfo(
    //           _latitude, _longitude, _location, loc?.adcode ?? "");
    //       setState(() {
    //         _location = _location != null && _location.isNotEmpty
    //             ? _location
    //             : "未获取定位信息";
    //       });
    //       _getData();
    //     } else {
    //       if (!isGetLocationInfoing &&
    //           _latitude != null &&
    //           _latitude.isNotEmpty &&
    //           _latitude != 'null' &&
    //           _longitude != null &&
    //           _longitude.isNotEmpty &&
    //           _longitude != 'null') {
    //         _getLocationInfo(_latitude, _longitude);
    //         setState(() {
    //           _location = "正在定位...";
    //         });
    //       } else {
    //         _getData();
    //         setState(() {
    //           _location = "未获取定位信息";
    //         });
    //       }
    //     }
    //   } else {
    //     _getData();
    //   }
    //   String locationResult = getLocationStr(loc);
    //   print("<Location> " + locationResult);

    //   AMapLocationClient.stopLocation();
    //   AMapLocationClient.shutdown();
    // });

    // AMapLocationClient.stopLocation();
    // AMapLocationClient.startLocation();
  }

  _handLocation(AMapLocation loc) {
    if (!mounted) return;
    if (loc != null) {
      _latitude = loc.latitude.toString();
      _longitude = loc.longitude.toString();
      _adcode = loc.adcode ?? "";

      switch (_regionLevel) {
        case 1:
          // 省级名称
          _location = loc?.province ?? "";
          break;
        case 2:
          // 市级名称
          _location = loc?.city ?? (loc?.province ?? "");
          break;
        case 3:
          // 县区级名称
          _location = loc?.district ?? (loc?.city ?? (loc?.province ?? ""));
          break;
        default:
          _location = loc?.district ?? (loc?.city ?? (loc?.province ?? ""));
      }
      if (_location != null && _location.isNotEmpty) {
        Location.saveLocationInfo(
            _latitude, _longitude, _location, loc?.adcode ?? "");
        setState(() {
          _location =
              _location != null && _location.isNotEmpty ? _location : "未获取定位信息";
        });
        _getData();
      } else {
        if (!isGetLocationInfoing &&
            _latitude != null &&
            _latitude.isNotEmpty &&
            _latitude != 'null' &&
            _longitude != null &&
            _longitude.isNotEmpty &&
            _longitude != 'null') {
          _getLocationInfo(_latitude, _longitude);
          setState(() {
            _location = "正在定位...";
          });
        } else {
          _getData();
          setState(() {
            _location = "未获取定位信息";
          });
        }
      }
    } else {
      _getData();
    }
    String locationResult = getLocationStr(loc);
    print("<Location> " + locationResult);
  }

  _checkPersmission() async {
    if (Platform.isIOS) {
      _startLocation();
    } else {
      final Future<PermissionStatus> statusFuture =
          PermissionHandler().checkPermissionStatus(PermissionGroup.location);

      statusFuture.then((PermissionStatus status) {
        if (status == PermissionStatus.granted) {
          _startLocation();
        } else {
          final List<PermissionGroup> permissions = <PermissionGroup>[
            PermissionGroup.location
          ];
          final Future<Map<PermissionGroup, PermissionStatus>> requestFuture =
              PermissionHandler().requestPermissions(permissions);

          requestFuture.then(
              (Map<PermissionGroup, PermissionStatus> permissionRequestResult) {
            PermissionStatus status =
                permissionRequestResult[PermissionGroup.location];
            if (status == PermissionStatus.granted) {
              _startLocation();
            } else {
              ToastUtil.showMessageToast("定位授权失败，无法获取定位信息");
              _startLocation();
            }
          });
        }
      });
    }

    // if (Platform.isIOS) {
    //   _startLocation();
    // } else {
    //   bool hasPermission =
    //       await SimplePermissions.checkPermission(Permission.WhenInUseLocation);
    //   if (!hasPermission) {
    //     PermissionStatus requestPermissionResult =
    //         await SimplePermissions.requestPermission(
    //             Permission.WhenInUseLocation);
    //     if (requestPermissionResult == PermissionStatus.authorized) {
    //       _startLocation();
    //     } else {
    //       ToastUtil.showMessageToast("定位授权失败，无法获取定位信息");
    //       _startLocation();
    //     }
    //   } else {
    //     _startLocation();
    //   }
    // }
  }

  String getLocationStr(AMapLocation loc) {
    if (loc == null) {
      return "正在定位...";
    }

    if (loc.isSuccess()) {
      if (loc.hasAddress()) {
        print("<Location> accuracy " + loc?.accuracy?.toString() ?? '');
        print("<Location> adcode " + loc?.adcode?.toString() ?? '');
        print("<Location> altitude " + loc?.altitude?.toString() ?? '');
        print("<Location> AOIName " + loc?.AOIName ?? '');
        print("<Location> city " + loc?.city ?? '');
        print("<Location> citycode " + loc?.citycode ?? '');
        print("<Location> code " + loc?.code?.toString() ?? '');
        print("<Location> country " + loc?.country ?? '');
        print("<Location> district " + loc?.district ?? '');
        print("<Location> formattedAddress " + loc?.formattedAddress ?? '');
        print("<Location> latitude " + loc?.latitude?.toString() ?? '');
        print("<Location> locationType " + loc?.locationType?.toString() ?? '');
        print("<Location> longitude " + loc?.longitude?.toString() ?? '');
        print("<Location> number " + loc?.number ?? '');
        print("<Location> POIName " + loc?.POIName ?? '');
        print("<Location> provider " + loc?.provider ?? '');
        print("<Location> province " + loc?.province ?? '');
        print("<Location> speed " + loc?.speed?.toString() ?? '');
        print("<Location> street " + loc?.street?.toString() ?? '');
        print("<Location> success " + loc?.success?.toString() ?? '');
        print("<Location> timestamp " + loc?.timestamp?.toString() ?? '');

        return "定位成功: \n时间${loc.timestamp}\n经纬度:${loc.latitude} ${loc.longitude}\n 地址:${loc.formattedAddress} 城市:${loc.city} 省:${loc.province}";
      } else {
        return "定位成功: \n时间${loc.timestamp}\n经纬度:${loc.latitude} ${loc.longitude}\n ";
      }
    } else {
      return "定位失败: \n错误:{code=${loc.code},description=${loc.description}";
    }
  }

  _getData() {
    _getUserInfoFromLocate();
    _getAdvertisements();
    _getSwiper();
    _getNotices();
    _getRecommend(true);
    _getBrands();
    _getChannels();
    _getHeadLines(_latitude, _longitude, _adcode);
    _getHotTags();
  }

  _getAdvertisements() {
    Map<String, String> params = {"page_name": "home_page"};
    NetUtil.get(context, Api.advertisements, (data, message) {
      if (!mounted) return;
      setState(() {
        _homeAdvertisements = (data as List)
            ?.map((e) => e == null ? null : Advertisement.fromJson(e))
            ?.toList();
      });
    }, params: params, errorCallBack: (e) {});
  }

  _getSwiper() {
    NetUtil.get(context, Api.swipers, (data, message) {
      if (!mounted) return;
      setState(() {
        _advertisementImages = (data as List)
            ?.map((e) => e == null ? null : Advertisement.fromJson(e))
            ?.toList();
      });
    }, errorCallBack: (e) {});
  }

  _getNotices() {
    NetUtil.get(context, Api.pagesNotices, (data, message) {
      if (!mounted) return;
      setState(() {
        _notices = (data as List)
            ?.map((e) => e == null ? null : Notices.fromJson(e))
            ?.toList();
      });
    }, errorCallBack: (e) {});
  }

  _getRecommend(bool isNew) {
    NetUtil.get(context, Api.pagesRecommend, (data, message) {
      if (!mounted) return;
      setState(() {
        var _dataList = (data as List)
            ?.map((e) => e == null ? null : Product.fromJson(e))
            ?.toList();
        if (_dataList != null) {
          if (isNew) {
            _recommendProduct = _dataList;
          } else {
            _recommendProduct.addAll(_dataList);
          }
        }
      });
      if (_refreshListView != null) {
        _refreshListView.refreshCompleted(isNew);
      }
    }, errorCallBack: (e) {
      if (_refreshListView != null) {
        _refreshListView.refreshCompleted(isNew);
      }
    });
  }

  _getBrands() {
    NetUtil.get(context, Api.pagesBrands, (data, message) {
      if (!mounted) return;
      setState(() {
        _brands = (data as List)
            ?.map((e) => e == null ? null : Brand.fromJson(e))
            ?.toList();
      });
    }, errorCallBack: (e) {});
  }

  _getChannels() {
    Map<String, String> params = {"parent_id": "0"};
    NetUtil.get(context, Api.channels, (data, message) {
      if (!mounted) return;
      setState(() {
        _channels = (data as List)
            ?.map((e) => e == null ? null : Channel.fromJson(e))
            ?.toList();
      });
    }, params: params, errorCallBack: (e) {});
  }

  _getSeckills() {
    NetUtil.get(context, Api.pagesSeckills, (data, message) {
      if (!mounted) return;
      setState(() {
        _seckills = (data as List)
            ?.map((e) => e == null ? null : Seckills.fromJson(e))
            ?.toList();
      });
    }, errorCallBack: (e) {});
  }

  _getHeadLines(String latitude, String longitude, String adcode) {
    Map<String, String> params = {
      "latitude": latitude,
      "longitude": longitude,
      "adcode": adcode
    };
    NetUtil.get(context, Api.pageHeadLines, (data, message) {
      if (!mounted) return;
      setState(() {
        _headLines = (data as List)
            ?.map((e) => e == null ? null : HeadLine.fromJson(e))
            ?.toList();
      });
    }, params: params, errorCallBack: (e) {});
  }

  _getHotTags() {
    NetUtil.get(context, Api.hotTags, (data, message) {
      if (!mounted) return;
      setState(() {
        _hotTags = (data as List)
            ?.map((e) => e == null ? null : HotTag.fromJson(e))
            ?.toList();
      });
    }, errorCallBack: (e) {});
  }

  _getUserInfoFromLocate() async {
    await _user.getUserInfo();
  }

  bool isGetLocationInfoing = false;
  _getLocationInfo(String latitude, String longitude) async {
    isGetLocationInfoing = true;
    Map<String, String> params = {
      "location": longitude + "," + latitude,
      "key": Api.amapWebAppId,
      "extensions": "all",
    };

    Dio dio = new Dio();
    dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));

    Response response = await dio.get(
        "https://restapi.amap.com/v3/geocode/regeo",
        queryParameters: params);
    final responseData = response.data;
    print("<_getLocationInfo> data ");
    print(responseData);
    if (responseData['status'].toString() == "1" &&
        responseData['info'] == "OK") {
      if (!mounted) return;
      if (responseData["regeocode"] != null &&
          responseData["regeocode"]["addressComponent"] != null) {
        Map addressComponent = responseData["regeocode"]["addressComponent"];
        String _province = addressComponent["province"].toString() != "[]"
            ? addressComponent["province"].toString()
            : null;
        String _city = addressComponent["city"].toString() != "[]"
            ? addressComponent["city"].toString()
            : null;
        String _district = addressComponent["district"].toString() != "[]"
            ? addressComponent["district"].toString()
            : null;

        _adcode = addressComponent["adcode"].toString() != "[]"
            ? addressComponent["adcode"].toString()
            : null;

        switch (_regionLevel) {
          case 1:
            // 省级名称
            _location = _province ?? "";
            break;
          case 2:
            // 市级名称
            _location = _city ?? (_province ?? "");
            break;
          case 3:
            // 县区级名称
            _location = _district ?? (_city ?? (_province ?? ""));
            break;
          default:
            _location = _district ?? (_city ?? (_province ?? ""));
        }
        Location.saveLocationInfo(
            _latitude, _longitude, _location, _adcode ?? "");
        setState(() {
          _location =
              _location != null && _location.isNotEmpty ? _location : "未获取定位信息";
        });
      } else {
        setState(() {
          _location = "未获取定位信息";
        });
      }
    } else {
      setState(() {
        _location = "未获取定位信息";
      });
    }
    _getData();
    isGetLocationInfoing = false;
  }

  Future _scan() async {
    ScanResult barcode;
    String errorStr;
    try {
      var options = ScanOptions(
        strings: {
          "cancel": "取消",
          "flash_on": "打开闪光灯",
          "flash_off": "关闭闪光灯",
        },
        android: AndroidOptions(
          useAutoFocus: true,
        ),
      );

      barcode = await BarcodeScanner.scan(options: options);
      int _pId = int.parse(barcode.rawContent);
      if (_pId != null && _pId > 0) {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new GoodsDetailsPage(productId: _pId);
        }));
      }
      return;
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        errorStr = '未授权摄像头权限';
      } else {
        errorStr = 'Unknown error: $e';
      }
    } on FormatException {
      if (errorStr != null && errorStr.isNotEmpty) {
        errorStr = '数据解析有误, 请扫描正确的二维码';
      } else {
        return;
      }
    } catch (e) {
      errorStr = 'Unknown error: $e';
    }
    ToastUtil.showMessageToast(errorStr);
  }
}
